const mysql_query = require("../common/mysql");
const httpresult = require("../common/response");
const utils = require("../common/utils");
const define = require("../common/define");
const chapter_model = require("./chapter");
const question_model = require("../models/question");

async function create_question(course_id, description, stem, analysis, answer, type, chapter_id = null, bank_id = null, count = 1) {
    if (bank_id) {
        var [err, data] = await mysql_query("select course_id from bank where bank_id = ?", [bank_id]);
        if (err) {
            return [err, data];
        }
        course_id = data[0].course_id;
    }

    var [err, data] = await mysql_query("insert into question (course_id, description, stem, analysis, answer, type, chapter_id, count) value (?, ?, ?, ?, ?, ?, ?, ?)",
        [course_id, description, stem, analysis, answer, type, chapter_id || 0, count]);
    if (err) {
        return [err, data];
    }
    return [null, data.insertId];
}

async function destroy_question(question_id) {
    return await mysql_query("delete from question where question_id = ?", [question_id]);
}

async function list(condition){
    let sql = "select * from question where true ";
    let where_params = [];
    if (condition.hasOwnProperty("question_ids")) {
        sql += "and question_id in (?)";
        where_params.push(condition.question_ids);
    }
    let [err, data] = await mysql_query(sql, where_params);
    if (err) {
        return [err, null];
    }
    for (let index in data) {
        data[index].description = utils.add_src_host(data[index].description);
        data[index].stem = utils.add_src_host(data[index].stem);
        data[index].analysis = utils.add_src_host(data[index].analysis);
        data[index].answer = utils.add_src_host(data[index].answer);
    }
    if (condition.hasOwnProperty("question_ids")) {
        let order = condition.question_ids.reduce((result, name, index) => {
            result[name] = index;
            return result;
        }, {});
        data.sort((next, prev) => {
            return order[next.question_id] > order[prev.question_id] ? 1 : -1;
        });
    }
    return [null, data];
}

async function get_questions (course_id, question_ids_json) {
    let question_ids = JSON.parse(question_ids_json);
    let [err, questions] = await question_model.list({"question_ids": question_ids});
    if (err) {
        return [err, null];
    }

    let total_index = 0;
    let question_set = {};
    for(let question of questions) {
        if (!question_set.hasOwnProperty(question.type)) {
            question_set[question.type] = [];
        }
        question["sub_question"] = [];
        question.stem = JSON.parse(question.stem);
        question.analysis = JSON.parse(question.analysis);
        question.answer = JSON.parse(question.answer);
        for (let i = 0; i < question.stem.length; ++ i) {
            total_index = question_set[question.type].length + question["sub_question"].length + 1;
            if (question.type === "choice") {
                question.description = question.description.replace("<u>（）</u>", "<u>（" + total_index +"）</u>");
            }
            question["sub_question"].push({
                total_index: total_index,
                stem: question.stem[i],
                analysis: question.analysis[i],
                answer: question.answer[i]
            });
        }
        question_set[question.type].push(question);
    }
    return [null, question_set];
}

async function get_questions_with_chapter (course_id, question_ids_json) {
    let question_ids = JSON.parse(question_ids_json);
    let [err, questions] = await question_model.list({"question_ids": question_ids});
    if (err) {
        return [err, null];
    }
    let question_set = {chapter_parent:[]};

    [err, chapters] = await chapter_model.list({course_id: course_id});
    if (err) {
        return [err, null];
    }
    let chapters_obj = {};
    for (let chapter of chapters) {
        chapters_obj[chapter.chapter_id] = chapter;
    }
    let total_index_obj = {}
    // 整理子题目
    for(let question of questions) {
        if (!chapters_obj[question.chapter_id].hasOwnProperty(question.type)) {
            chapters_obj[question.chapter_id][question.type] = [];
        }

        question["sub_question"] = [];
        question.stem = JSON.parse(question.stem);
        question.analysis = JSON.parse(question.analysis);
        question.answer = JSON.parse(question.answer);
        for (let i = 0; i < question.stem.length; ++ i) {
            let total_index = 0
            if (chapters_obj[question.chapter_id][question.type].length == 0) {
                total_index = i + 1;
            } else {
                let last_question = chapters_obj[question.chapter_id][question.type][chapters_obj[question.chapter_id][question.type].length - 1];
                total_index = last_question["sub_question"][0].total_index
                    + last_question["sub_question"].length - 1 + i + 1;
            }
            // total_index = chapters_obj[question.chapter_id][question.type].length + question["sub_question"].length + 1;
            if (question.type === "choice") {
                // 因为在题干的循环里，所以每次循环只需要replace一个<u>（）</u>即可。
                question.description = question.description.replace(/<u>（.*?）<\/u>/, "<u>（" + total_index +"）</u>");
            }
            else if (question.type === "fillup") {
                // 如果是填空题，目前设置的是：即使多个空，也属于一道子题目
                question.description = question.description.replaceAll(/<u>（.*?）<\/u>/g, "<u>（" + total_index +"）</u>");
            }
            question["sub_question"].push({
                total_index: total_index,
                stem: question.stem[i],
                analysis: question.analysis[i],
                answer: question.answer[i]
            });
        }

        chapters_obj[question.chapter_id][question.type].push(question);
    }

    // 章节整理
    let chapter_parent_obj = {};

    // 提取父级章节目录
    for (let chapter of Object.values(chapters_obj)) {
        if (chapter.parent_id === 0) {
            if (!chapter_parent_obj.hasOwnProperty(chapter.chapter_id)) {
                chapter_parent_obj[chapter.chapter_id] = chapter;
            }
        }
    }

    // 归类子级章节目录
    for (let chapter of Object.values(chapters_obj)) {
        if (chapter.parent_id === 0) {
            continue;
        }
        if (!chapter_parent_obj[chapter.parent_id].hasOwnProperty("chapter_sub")) {
            chapter_parent_obj[chapter.parent_id]["chapter_sub"] = [];
        }
        chapter["parent_order"] = chapter_parent_obj[chapter.parent_id].order_number
        chapter_parent_obj[chapter.parent_id]["chapter_sub"].push(chapter);
    }
    for (let chapter_parent_id of Object.keys(chapter_parent_obj)) {
        if (chapter_parent_obj[chapter_parent_id].hasOwnProperty("chapter_sub")) {
            chapter_parent_obj[chapter_parent_id]["chapter_sub"] = Object.values(chapter_parent_obj[chapter_parent_id]["chapter_sub"]);
            chapter_parent_obj[chapter_parent_id]["chapter_sub"] = chapter_parent_obj[chapter_parent_id]["chapter_sub"].sort((a, b) => {
                return a.order_number - b.order_number;
            })
        }
    }
    question_set.chapter_parent = Object.values(chapter_parent_obj);
    question_set.chapter_parent = question_set.chapter_parent.sort((a, b) => {
        return a.order_number - b.order_number;
    });

    return [null, question_set];
}


exports.createQuestion = create_question;
exports.destroy_question = destroy_question;
exports.list = list;
exports.get_questions_with_chapter = get_questions_with_chapter;
exports.get_questions = get_questions;